<template>
  <div :class="{ 'editor-box': props.border }">
    <Toolbar style="border-bottom: 1px solid #e3e3e3" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor :style="{ height: props.height + 'px', 'overflow-y': 'hidden'}" v-model="props.html" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
  </div>
</template>

<script setup>
import { onBeforeUnmount, shallowRef, defineEmits, onMounted } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue' //引入插件的实例组件=
// import { createEditor } from '@wangeditor/editor'////查看工具栏所有可配置的key

import { uploadImgGetUrlApi} from '@/api/public/uploadFile.js'
import { useStore } from 'vuex';
const store = useStore()

// onMounted(() => {
//   const editor = createEditor({})
//     console.log(editor.getConfig(),999999);//查看工具栏所有可配置的key
// })



const props = defineProps({
  //回显html文本
  html: {
    type: String,
    default: () => '<p><br></p>',
  },
  //编辑器的个数，同一页面用于区分多个编辑器
  type: {
    type: Number,
    default: 0,
  },
  //最外层边框是否显示
  border: {
    type: Boolean,
    default: true,
  },
  //文本编辑区域内容高度
  height: {
    type: Number,
    default: 300,
  },
})

//父组件传来的函数方法
const emit = defineEmits(['textEdit'])

//组件卸载前移除实例
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

//编辑菜单实例响应式
const editorRef = shallowRef()

//功能菜单配置
const toolbarConfig = {
  excludeKeys: ['group-video', 'codeBlock','insertImage','fullScreen']
}

//编辑的文本内容配置
const editorConfig = {
  placeholder: '...',
  MENU_CONF: {
    //上传图片
    uploadImage: {
        async customUpload(file, insertFn) {
        let fd = new FormData()
        fd.append('file', file)
        const url = await uploadImgGetUrlApi(fd).then(res => {
          if (res.status === 200) {
            return res.data
          }
        })
        insertFn(url)
      },
    }
  }
}

//编辑输入赋值
const handleCreated = (editor) => {
  editorRef.value = editor
}

//当进行输入相关操作时，返回文本内容或着带html标签的内容
const handleChange = (editor) => {
  //   console.log(editor.children)
  //   console.log(editor.getHtml())
  emit('textEdit', editor.getHtml(), props.type)
}
</script>

<style lang="scss" scoped>
.editor-box {
  border: 1px solid #e3e3e3;
  width: 100%;
}
</style>